package com.boguan.web.controller.device;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.boguan.common.annotation.Log;
import com.boguan.common.annotation.RepeatSubmit;
import com.boguan.common.config.ProjectConfig;
import com.boguan.common.constant.UserConstants;
import com.boguan.common.core.controller.BaseController;
import com.boguan.common.core.domain.AjaxResult;
import com.boguan.common.core.domain.entity.SysUser;
import com.boguan.common.core.page.TableDataInfo;
import com.boguan.common.utils.SecurityUtils;
import com.boguan.common.utils.StringUtils;
import com.boguan.common.utils.file.FileUploadUtils;
import com.boguan.common.utils.file.FileUtils;
import com.boguan.device.domain.Device;
import com.boguan.device.domain.DeviceType;
import com.boguan.device.domain.DeviceTypeParam;
import com.boguan.device.service.IDeviceService;
import com.boguan.device.service.IDeviceTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/device/type")
@Api(tags = "设备类型")
public class DeviceTypeController extends BaseController {

    @Autowired
    private IDeviceTypeService deviceTypeService;

    @Autowired
    private IDeviceService deviceService;


    /**
     * 创建设备类型
     */
    @ApiOperation("创建设备类型")
    @PostMapping("create")
    @RepeatSubmit
    public AjaxResult createDeviceType(@RequestBody DeviceType deviceType) {
        if (StringUtils.isNull(deviceType.getName())) {
            return AjaxResult.error("设备类型名称不能为空");
        } else if (StringUtils.isNull(deviceType.getIcon())) {
            return AjaxResult.error("设备类型图标不能为空");
        } else if (StringUtils.isNull(deviceType.getModelNumber())) {
            return AjaxResult.error("产品型号不能为空");
        } else {
            try {
                JSONObject.parseObject(deviceType.getModelNumber(), List.class);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("产品型号格式不正确，必须是 数组转化未json形式的字符串");
            }
        }
        return toAjax(deviceTypeService.createDeviceType(deviceType));
    }


    /**
     * 设备类型图片上传
     *
     * @param file
     * @return
     */
    @ApiOperation("上传设备文件地址")
    @PostMapping("icon")
    public AjaxResult deviceTypeIcon(@RequestParam("file") MultipartFile file) {
        AjaxResult ajaxResult = AjaxResult.success();
        //文件校验后缀
//        String originalFilename = file.getOriginalFilename();
//        String substring = originalFilename.substring(originalFilename.lastIndexOf("."));
//        if (!substring.equalsIgnoreCase(".jpg")||) {
//            return AjaxResult.error("不是jpg文件");
//        }
        String upload = null;
        try {
            upload = FileUploadUtils.upload(ProjectConfig.getUploadPath(), file);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ajaxResult.put("filename", upload);
        return ajaxResult;
    }

    @ApiOperation("查询出设备类型列表或者设备类型下拉框")
    @GetMapping("/list")
    public TableDataInfo searchPage(DeviceType deviceType) {
        startPage();
        List<DeviceType> list = deviceTypeService.searchPage(deviceType);
        return getDataTable(list);
    }

    @ApiOperation("根据设备类型id查询设备类型详情")
    @GetMapping("/{typeId}")
    public AjaxResult selectTypeDetails(@PathVariable("typeId") Long typeId) {

        DeviceType deviceType = deviceTypeService.selectTypeDetails(typeId);
        return AjaxResult.success(deviceType);
    }

    @ApiOperation("设备类型信息修改")
    @PutMapping("update")
    public AjaxResult updateDeviceType(@RequestBody DeviceType deviceType) {
        DeviceType checkDeviceType = deviceTypeService.selectDeviceTypeByTypeId(deviceType.getTypeId());
        if (StringUtils.isNull(checkDeviceType)) {
            return AjaxResult.error("该类型已经被删除或信息不存在");
        } else if (StringUtils.isNull(deviceType.getModelNumber())) {
            return AjaxResult.error("产品型号不能为空");
        } else {
            try {
                JSONObject.parseObject(deviceType.getModelNumber(), List.class);
            } catch (Exception e) {
                e.printStackTrace();
                return AjaxResult.error("产品型号格式不正确，必须是 数组转化未json形式的字符串");
            }
        }
        if (StringUtils.isNotNull(deviceType.getIcon())) {
            //校验图片是否相等
            if (!deviceType.getIcon().equals(checkDeviceType.getIcon())) {
                FileUtils.deleteFile(checkDeviceType.getIcon());
            }
        }
        return toAjax(deviceTypeService.updateDeviceType(deviceType));
    }

    @Log(title = "删除设备类型")
    @ApiOperation("删除设备类型")
    @DeleteMapping("delete/{typeId}")
    @RepeatSubmit
    public AjaxResult deleteDeviceType(@PathVariable("typeId") Long typeId) {
        //校验设备类型是否又设备绑定
        List<Device> devices = deviceService.selectDeviceByTypeId(typeId);
        if (StringUtils.isNotEmpty(devices)) {
            return AjaxResult.error("该设备类型绑定了设备信息，无法删除！！！");
        }
        return toAjax(deviceTypeService.deleteDeviceType(typeId));
    }


    @ApiOperation("根据设备类型id查询出设备组态信息")
    @GetMapping("/param/list")
    public TableDataInfo selectDeviceTypeParam(DeviceTypeParam deviceTypeParam) {

        startPage();
        List<DeviceTypeParam> list = deviceTypeService.selectDeviceTypeParam(deviceTypeParam);
        return getDataTable(list);
    }

    @Log(title = "创建设备类型组态")
    @ApiOperation("创建设备类型组态")
    @PostMapping("/param/create")
    @RepeatSubmit
    public AjaxResult createDeviceTypeParam(@RequestBody DeviceTypeParam deviceTypeParam) {
        DeviceType deviceType = deviceTypeService.selectDeviceTypeByTypeId(deviceTypeParam.getTypeId());
        if (StringUtils.isNull(deviceType)) {
            return AjaxResult.error("设备类型不存在");
        } else if (StringUtils.isNull(deviceTypeParam.getParamName())) {
            return AjaxResult.error("请输入组态名称");
        } else if (StringUtils.isNull(deviceTypeParam.getParamType())) {
            return AjaxResult.error("请选择组态类型");
        } else if (StringUtils.isNull(deviceTypeParam.getIdentifier())) {
            return AjaxResult.error("请输入组态的标识");
        } else if (UserConstants.NOT_UNIQUE.equals(deviceTypeService.checkIdentifier(deviceTypeParam))) {
            return AjaxResult.error("该组态标识已经存在");
        } else if (deviceTypeParam.getDataType() == 2) {
            try {
                Map<String, String> units = new HashMap<>();
                JSONArray jsonArray = JSONObject.parseArray(deviceTypeParam.getParamUnits());
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (StringUtils.isNotNull(units.get(jsonObject.getString("key")))) {
                        return AjaxResult.error("key值 '" + jsonObject.getString("key") + "' 重复出现");
                    }
                    units.put(jsonObject.getString("key"), jsonObject.getString("value"));
                }
                deviceTypeParam.setParamUnits(JSONObject.toJSONString(units));
            } catch (Exception e) {
                return AjaxResult.error("枚举的值格式错误");
            }
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        deviceTypeParam.setCreateTime(new Date());
        deviceTypeParam.setCreateUser(user.getUserId());
        return toAjax(deviceTypeService.createDeviceTypeParam(deviceTypeParam));
    }


    @Log(title = "修改更新设备类型组态")
    @ApiOperation("修改更新设备类型组态")
    @PutMapping("/param/update")
    @RepeatSubmit
    public AjaxResult updateDeviceTypeParam(@RequestBody DeviceTypeParam deviceTypeParam) {
        DeviceType deviceType = deviceTypeService.selectDeviceTypeByTypeId(deviceTypeParam.getTypeId());
        if (StringUtils.isNull(deviceType)) {
            return AjaxResult.error("设备类型不存在");
        } else if (StringUtils.isNull(deviceTypeParam.getParamName())) {
            return AjaxResult.error("请输入组态名称");
        } else if (StringUtils.isNull(deviceTypeParam.getParamType())) {
            return AjaxResult.error("请选择组态类型");
        } else if (StringUtils.isNull(deviceTypeParam.getIdentifier())) {
            return AjaxResult.error("请输入组态的标识");
        } else if (UserConstants.NOT_UNIQUE.equals(deviceTypeService.checkIdentifier(deviceTypeParam))) {
            return AjaxResult.error("该组态标识已经存在");
        } else if (deviceTypeParam.getDataType() == 2) {
            try {
                Map<String, String> units = new HashMap<>();
                JSONArray jsonArray = JSONObject.parseArray(deviceTypeParam.getParamUnits());
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    if (StringUtils.isNotNull(units.get(jsonObject.getString("key")))) {
                        return AjaxResult.error("key值 '" + jsonObject.getString("key") + "' 重复出现");
                    }
                    units.put(jsonObject.getString("key"), jsonObject.getString("value"));
                }
                deviceTypeParam.setParamUnits(JSONObject.toJSONString(units));
            } catch (Exception e) {
                return AjaxResult.error("枚举的值格式错误");
            }
        }
        SysUser user = SecurityUtils.getLoginUser().getUser();
        deviceTypeParam.setUpdateTime(new Date());
        deviceTypeParam.setUpdateUser(user.getUserId());
        return toAjax(deviceTypeService.updateDeviceTypeParam(deviceTypeParam));
    }

    @Log(title = "删除设备类型组态")
    @ApiOperation("删除设备类型组态")
    @PutMapping("/param/{paramId}")
    @RepeatSubmit
    public AjaxResult deviceDeviceTypeParam(@PathVariable("paramId") Long paramId) {

        return toAjax(deviceTypeService.deleteDeviceTypeParam(paramId));
    }

    @ApiOperation("根据组态id查询出组态详情")
    @GetMapping("/param/{paramId}")
    public AjaxResult getDeviceTypeParam(@PathVariable("paramId") Long paramId) {

        return AjaxResult.success(deviceTypeService.selectDeviceTypeParamByParamId(paramId));
    }


}
